const { TABLE_NAME } = require('../models');
const DbService = require('./db2');
const BaseService = require('./base');

class ContractService extends BaseService {
  constructor() {
    super();
    this.dbService = new DbService(TABLE_NAME.contract);
  }

  async create(data) {
    const flowId = data?.FlowId;
    return this.dbService.insert({ ...data, id: flowId });
  }

  // 回调状态更新
  async updateCallbackChangeStatus(flowId, data) {
    try {
      const target = await this.dbService.getById(flowId);
      if (!target) return {};
      return await this.dbService.updateById(flowId, data);
    } catch (err) {
      // logger.error({
      //   action: 'updateCallbackChangeStatus',
      //   ...data,
      //   errMessage: err.message,
      // });
      console.error({
        action: 'updateCallbackChangeStatus',
        ...data,
        errMessage: err.message,
      });
    }
  }

  async searchWithFilter({ flowName, offset, limit}) {
    let result = this.dbService.knex.select().from(TABLE_NAME.contract)
    if(flowName){
      result = result.whereILike(`${TABLE_NAME.contract}.FlowName`, `%${flowName}%`);
    }
    result =result.limit(limit)
    .offset(offset);
    return result
  }

  async countWithFilter({ flowName }) {
    let result = this.dbService.knex(TABLE_NAME.contract);
    if (flowName) {
      result = result.whereILike('FlowName', `%${flowName}%`);
    }
    const [{ count }] = await result.count({ count: '*' });
    return count;
  }
}

module.exports = ContractService;
